import uuid

from addict import Dict
from django.http.response import JsonResponse
from django_redis import get_redis_connection
from rest_framework.views import APIView

from utils.myResFormat import ResultJson, ResultCode
from web.captchaImage import CaptchaImage

RedisClient = get_redis_connection()


class CaptchaImageView(APIView):

    def get(self, request, *args, **kwargs):
        """【系统用户】获取验证码"""
        captcha = CaptchaImage()

        # 生成验证码图片和字符串
        captcha_string, image_base64 = captcha.generate(width=120, height=40)

        res = Dict()
        uid = uuid.uuid4().hex
        res.img = image_base64
        res.uuid = uid
        res.captchaEnabled = True

        RedisClient.set(uid, captcha_string, ex=5 * 60)

        return JsonResponse(ResultJson(ResultCode.SUCCESS, data=res.to_dict()).result)


class LoginView(APIView):
    "登录"

    def get(self, request, *args, **kwargs):
        return JsonResponse(ResultJson(ResultCode.SUCCESS).result)


class LogoutView(APIView):
    "退出登录"

    def post(self, request, *args, **kwargs):
        return JsonResponse(ResultJson(ResultCode.SUCCESS).result)


class GetInfoView(APIView):
    "获取登陆信息"

    def post(self, request, *args, **kwargs):
        return JsonResponse(ResultJson(ResultCode.SUCCESS).result)


class GetRoutersView(APIView):
    "获取用户权限路由"

    def post(self, request, *args, **kwargs):
        return JsonResponse(ResultJson(ResultCode.SUCCESS).result)
